package edu.nju.desserthouse.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nju.edu.desserthouse.model.Clerk;
import edu.nju.desserthouse.dao.ClerkDao;

/**
 * Servlet implementation class ClerkLogInServlet
 */
@WebServlet("/login.clerk")
public class ClerkLogInServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    
	@EJB
	ClerkDao clerkDao;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ClerkLogInServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		execute(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		execute (request, response);
	}
	
	public void execute(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		
		String account;
		String password;
		
		account = req.getParameter("account");
		password = req.getParameter("password");
		
		Clerk clerk = clerkDao.find("account", account, "password", password,0);
		
		if(clerk != null){
			req.getSession().setAttribute("clerk_id",clerk.getId());
			req.getSession().setAttribute("clerk_account",clerk.getAccount());
			req.getSession().setAttribute("clerk_belong",clerk.getBelong());
			resp.sendRedirect("/desserthouseWEB/clerk/clerkwelcome.jsp");
		}else{
			clerk = clerkDao.find("account", account, "password", password,1);
			if(clerk != null){
				req.getSession().setAttribute("clerk_id",clerk.getId());
				req.getSession().setAttribute("clerk_account",clerk.getAccount());
				req.getSession().setAttribute("clerk_belong",clerk.getBelong());
				resp.sendRedirect("/desserthouseWEB/clerk/clerkwelcome.jsp");
			}else{
				System.out.println("Wrong Input!!!");
				resp.sendRedirect("/desserthouseWEB/error/loginerror.jsp");
			}
		}
	}
}
